package com.ruoyi.framework.interceptor.advice;


import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.resource.OperatorUserSystem;
import com.ruoyi.common.utils.sign.AES;
import com.ruoyi.framework.utils.SessionHelper;
import com.ruoyi.framework.utils.UserLocalThreadHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Optional;

/**
 * @Author xiaom
 * @Date 2020/12/16 18:14
 * @Version 1.0.0
 * @Description <>
 **/
@ControllerAdvice(basePackages = "com.ruoyi.core.controller")
@Component
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice {

    private static final Logger logger = LoggerFactory.getLogger(GlobalResponseBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {

        Optional<String> en = SessionHelper.getRequestHeader(Constants.Encryption);

        if(en.isPresent() && en.get().equals("false")){
            return false;
        }

        if(SessionHelper.isClientRequest() || SessionHelper.isPluginRequest()){
            return true;
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        logger.debug("Response Data:{}", JSON.toJSONString(o));
        //加密
        try {
            String encStr = AES.encryptAES(JSON.toJSONString(o));
            logger.debug("加密文本：{}",encStr);
            return encStr;
        } catch (Exception e) {
            logger.error("加密响应参数失败 e:{}",e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }
}
